﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using NetCoreBBS.Infrastructure;
using NetCoreBBS.Entities;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace NetCoreBBS.ViewComponents
{
    public class TopicRankList: ViewComponent
    {
        private readonly DataContext db;
        private IMemoryCache _memoryCache;
        private string cachekey = "topicrank";
        private IUserServices _user;
        private UserManager<ApplicationUser> _userManager;

        public TopicRankList(DataContext context, 
            IMemoryCache memoryCache,
            IUserServices user,
            UserManager<ApplicationUser> userManager)
        {
            db = context;
            _memoryCache = memoryCache;
            _user = user;
            _userManager = userManager;
        }

        public IViewComponentResult Invoke(int days)
        {
            var items = new List<Topic>();
            if (!_memoryCache.TryGetValue(cachekey, out items))
            {
                items = GetRankTopics(10, days).Result;
                _memoryCache.Set(cachekey, items, TimeSpan.FromMinutes(10));
            }
            return View(items);
        }
        /// <summary>
        /// 获取主题排行
        /// </summary>
        /// <param name="top"></param>
        /// <param name="days"></param>
        /// <returns></returns>
        private async Task<List<Topic>> GetRankTopics(int top,int days)
        {
            var currentUser = _user.User.Result;
            if (currentUser == null)
                return new List<Topic>();

            bool isSuper = false;
            var claims = await _userManager.GetClaimsAsync(currentUser);
            foreach (var c in claims)
            {
                if (c.Type == ClaimTypes.Role && c.Value == "Admin" || c.Type == ClaimTypes.Role && c.Value == "Superman")
                {
                    isSuper = true;
                    break;
                }
            }
            if (isSuper)
            {
                return db.Topics.Where(r => r.CreateTime > DateTime.Now.AddDays(-days))
               .OrderByDescending(r => r.ViewCount).Take(top).ToList();
            }
            else
            {
                return db.Topics.Where(r => r.DepartmentId == currentUser.DepartmentId && r.CreateTime > DateTime.Now.AddDays(-days))
               .OrderByDescending(r => r.ViewCount).Take(top).ToList();
            }

           
        }
    }
}
